package com.banciyuan.bcywebview.biz.register;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PhoneValidActivity extends BaseActivity implements View.OnClickListener {

    protected EditText mEtPhone;
    private EditText mEtAuthCode;
    private View mViewGetCode;
    protected RequestQueue mQueue;
    protected String phoneNum;
    protected String code;
    private TextView mViewCountDown;
    protected TextView mTvPageTitle;
    private int REFRESH_COUNTDOWN = 100;
    private int countdown_time = 60;
    protected boolean is_send;
    protected boolean has_post;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == REFRESH_COUNTDOWN) {
                if (countdown_time > 0) {
                    countdown_time--;
                    mViewCountDown.setText(String.format(getString(R.string.countdown_format), countdown_time));
                    mHandler.sendEmptyMessageDelayed(REFRESH_COUNTDOWN, 1000);
                } else {
                    mViewCountDown.setVisibility(View.GONE);
                    mViewGetCode.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.phone_verify_layout);
        initArgs();
        initUi();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initUi() {
        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mEtAuthCode = (EditText) findViewById(R.id.et_auth_code);
        mViewGetCode = findViewById(R.id.view_code);
        mViewCountDown = (TextView) findViewById(R.id.view_code_countdown);
        mTvPageTitle = (TextView) findViewById(R.id.tv_basephone_title);
        findViewById(R.id.iv_cancle).setOnClickListener(this);
        findViewById(R.id.tv_auth).setOnClickListener(this);
        findViewById(R.id.iv_cancle_phone).setOnClickListener(this);
        mViewGetCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cancle:
                gotoNextActivity();
                break;
            case R.id.tv_auth:
                code = mEtAuthCode.getText().toString().trim();
                phoneNum = mEtPhone.getText().toString().trim();
                if (vaildCode() && validPhone()) {
                    bindMobile();
                }
                break;
            case R.id.view_code:
                phoneNum = mEtPhone.getText().toString().trim();
                if (validPhone()) {
                    mViewGetCode.setVisibility(View.INVISIBLE);
                    mViewCountDown.setVisibility(View.VISIBLE);
                    countdown_time = 60;
                    mHandler.sendEmptyMessage(REFRESH_COUNTDOWN);
                    requestCode();
                }
                break;
            case R.id.iv_cancle_phone:
                mEtPhone.setText("");
                break;
        }
    }

    private boolean vaildCode() {
        boolean empty = TextUtils.isEmpty(code);
        if (empty) {
            MyToast.show(this, getString(R.string.input_code));
        }
        return !empty;
    }

    protected void bindMobile() {
        if (is_send) return;
        is_send = true;
        String url = HttpUtils.BASE_URL + UserApi.bindMobile();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.MOBILE, phoneNum));
        paramsList.add(new BcyPair(HttpUtils.CODE, code));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                is_send = false;
                try {
                    JSONObject result = new JSONObject(s);
                    MyToast.show(PhoneValidActivity.this, result.getString(HttpUtils.UPLOAD_DATA));
                    if ("1".equals(result.getString("status"))) {
                        gotoNextActivity();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                is_send = false;
            }
        };
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, error);
        mQueue.add(stringRequest);
    }

    protected void gotoNextActivity() {
        gotoUtil.replaceAct(PhoneValidActivity.this, RegisterChooseHeadActivity.class);
    }

    private boolean validPhone() {
        boolean matches = phoneNum.matches("^\\d{11}$");
        if (!matches) {
            MyToast.show(this, getString(R.string.unvalid_phonenum));
        }
        return matches;
    }

    protected void requestCode() {
        if (has_post) return;
        has_post = true;
        String url = HttpUtils.BASE_URL + UserApi.requestCode();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.MOBILE, phoneNum));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                has_post=false;
                try {
                    if (StatusCodeUtils.dealStatusCode(s, PhoneValidActivity.this)) {
                        JSONObject result = new JSONObject(s);
                        MyToast.show(PhoneValidActivity.this, result.getString(HttpUtils.UPLOAD_DATA));
                    } else {
                        resetCodeHandler();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                has_post=false;
            }
        };
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, error);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(15000, 0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(stringRequest);
    }

    protected void resetCodeHandler() {
        countdown_time = 0;
        mHandler.sendEmptyMessage(REFRESH_COUNTDOWN);
    }
}
